<template>
  <div>
    <el-row>
      <el-col>
        <el-button @click="rolesDialogVisible = true;dialogTitle='新建角色'" type="primary">添加角色</el-button>
      </el-col>

    </el-row>

    <!-- 表格 -->
    <el-table border :data="userPowerList" stripe style="width: 100%" height="450">
      <!-- 展开 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- 每一行 -->
          <el-row class="bortom" v-for="(item) in scope.row.children" :key="item.id">
            <!-- 一级权限 -->
            <el-col :span="5">
              <el-tag closable @close="removeRightById(scope.row,item.id)">{{item.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 二级三级 -->
            <el-col :span="19">
              <el-row v-for="item2 in item.children" :key="item2.id">
                <!-- 二级权限 -->
                <el-col :span="6">
                  <el-tag closable @close="removeRightById(scope.row,item2.id)" type="success">{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级权限 -->
                <el-col :span="18">
                  <el-tag closable @close="removeRightById(scope.row,item3.id)" type="warning" v-for="item3 in item2.children" :key="item3.id">{{item3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#">
      </el-table-column>
      <el-table-column min-width="200px" prop="roleName" label="角色名称">
      </el-table-column>
      <el-table-column min-width="200px" prop="roleDesc" label="角色描述">
      </el-table-column>
      <el-table-column min-width="310px" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="changeDialog(scope.row)" icon="el-icon-edit">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="delRoles(scope.row)">删除</el-button>
          <el-tooltip :enterable="false" class="item" effect="dark" content="分配权限" placement="top">
            <el-button size="mini" type="warning" icon="el-icon-s-tools" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </el-tooltip>

        </template>
      </el-table-column>
    </el-table>
    <!-- 添加弹出框 -->
    <!-- 添加用户弹出框 -->
    <el-dialog v-dialogDrag :title="dialogTitle" :visible.sync="rolesDialogVisible" @close="closeAddDialog" width="50%">
      <!-- 表单 -->
      <el-form :rules="rolesFromRuls" ref="rolesFormRef" :model="rolesInfo">
        <el-form-item prop="roleName" label-width="80px" label="角色名称">
          <el-input v-model.trim="rolesInfo.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label-width="70px" label="角色描述">
          <el-input v-model.trim="rolesInfo.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="postRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户权限弹出框 -->
    <el-dialog @close="defRightList=[]" title="编辑权限" :visible.sync="RightDialog">
      <el-tree ref="rightsTreeRef" :data="rightList" :props="rightProps" show-checkbox node-key="id" :default-checked-keys="defRightList" default-expand-all></el-tree>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="RightDialog=false">取 消</el-button>
        <el-button type="primary" @click="postRolesRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserPowerListAPI, postRolesAPI, delRolesAPI, changeRolesAPI, deleteRightByIdAPI, getPowerListAPI, postRolesRightAPI } from '@/api/powerAPI'
export default {
  name: 'roles',
  data() {
    return {
      userPowerList: [],
      // 新建角色，编辑角色弹出框
      rolesDialogVisible: false,
      // 编辑角色弹出框
      RightDialog: false,
      dialogTitle: '新建角色',
      rolesInfo: {
        roleName: '',
        roleDesc: ''
      },
      roleId: '',
      rolesFromRuls: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
      },
      // 权限列表
      rightList: [],
      // 树形视图配置
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      // 渲染的节点
      defRightList: []
    }
  },
  methods: {
    async getUserPowerList() {
      const { data: res } = await getUserPowerListAPI()
      this.userPowerList = res.data
    },
    // 关闭对话框重置
    closeAddDialog() {
      console.log(this.$refs)
      this.$refs.rolesFormRef.resetFields()
      // 添加用户表单
      this.rolesInfo = {
        roleName: '',
        roleDesc: ''
      }
      this.roleId = ''
    },
    // 添加角色，以及修改角色
    postRoles() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return false
        // 如果id不为空那么说明正处于修改页面中
        if (this.roleId !== '') {
          console.log(this.roleId)
          const { data: res } = await changeRolesAPI(this.roleId, this.rolesInfo)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success('修改成功')
        } else {
          // 新建数据
          const { data: res } = await postRolesAPI(this.rolesInfo)
          if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success('添加成功')
        }

        this.rolesDialogVisible = false
        this.getUserPowerList()
      })
    },
    // 删除角色
    async delRoles(row) {
      const confirResult = await this.$confirm('此操作将永久删除该条数据，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirResult === 'confirm') {
        const { data: res } = await delRolesAPI(row.id)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('删除成功')
        this.getUserPowerList()
      }
    },
    // 删除角色权限
    async removeRightById(row, rightId) {
      const confirResult = await this.$confirm('此操作将永久删除该条数据，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirResult === 'confirm') {
        console.log('确认删除', row.id, rightId)
        const { data: res } = await deleteRightByIdAPI(row.id, rightId)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('移除权限成功')
        row.children = res.data
      }
    },
    // 分配用户权限对话框
    async showSetRightDialog(row) {
      const { data: res } = await getPowerListAPI('tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      this.roleId = row.id
      // 存放数据
      this.rightList = res.data
      // 调用递归递归出最后一层子节点添加到列表中
      this.getLeafKeys(row, this.defRightList)
      // this.defRightList = this.getLeafKeys(row, [])
      // 显示对话框
      this.RightDialog = true
    },
    // 分配角色对话框确定
    async postRolesRights() {
      // 获取选中以及半选中节点的key，拼接并转为字符串
      const arrStr = [...this.$refs.rightsTreeRef.getCheckedKeys(), ...this.$refs.rightsTreeRef.getHalfCheckedKeys()].join(',')
      // 发起请求
      const { data: res } = await postRolesRightAPI(this.roleId, arrStr)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('权限更新成功')
      // 重新渲染数据
      this.getUserPowerList()
      // 关闭对话框
      this.RightDialog = false
      this.roleId = ''
    },
    // 递归出最后一层子节点添加到列表中
    getLeafKeys(node, arr) {
      // 判断是否是最后一层
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果不是最后一层就继续递归(每一层有的childre里不止一个节点所以用for循环每一节点继续递归)
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 改变角色，点击按钮
    changeDialog(row) {
      this.dialogTitle = '编辑角色'
      this.rolesDialogVisible = true
      this.rolesInfo.roleName = row.roleName
      this.rolesInfo.roleDesc = row.roleDesc
      this.roleId = row.id
    }
  },
  created() {
    this.getUserPowerList()
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 7px;
}
.bortom {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
}
.bortom:nth-child(1) {
  border-top: 1px solid #eee;
}
</style>
